<template>
  <div class="wrap">
    <div class="header">
      <el-input ref="search" placeholder="请输入学生姓名" v-model="name" :disabled="false"></el-input>
      <el-button type="primary" plain @click="checkStuName">搜索</el-button>
      <el-button type="primary" plain @click="clearSearch()">重置</el-button>
      <el-button type="success" plain @click="centerDialogVisible = true">添加学生</el-button>
    </div>

    <!-- 添加学生 -->

    <el-dialog title="添加学生" :visible.sync="centerDialogVisible" width="30%" center>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="学号" prop="stuNum">
          <el-input v-model.number="ruleForm.stuNum" placeholder="仅支持数字类型"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model.number="ruleForm.account" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passwd">
          <el-input type="password" v-model="ruleForm.passwd" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm'),addStudent()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改学生 -->

    <el-dialog title="修改学生信息" :visible.sync="centerDialogVisible2" width="30%" center>
      <el-form :model="ruleForm2" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="学号" prop="stuNum">
          <el-input disabled v-model="ruleForm2.stuNum"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="stuName">
          <el-input v-model="ruleForm2.name"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input disabled v-model="ruleForm2.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passwd">
          <el-input v-model.number="ruleForm2.passwd"></el-input>
        </el-form-item>
        <el-form-item label="所属寝室" prop="dormNum">
          <el-select v-model="ruleForm2.dormNum" value-key="id" placeholder="请选择学生所属寝室">
            <el-option v-for="item in list" :key="item.id" :value="item" :label="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm2('ruleForm'),changeStudent()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 表格数据 -->

    <div class="main">
      <template>
        <el-table v-loading="loading" :data="StudentData" border style="width: 100%"
          current-change="handleCurrentChange">
          <el-table-column prop="stuNum" label="学号">
          </el-table-column>
          <el-table-column prop="stuName" label="姓名">
          </el-table-column>
          <el-table-column prop="userName" label="账号">
          </el-table-column>
          <el-table-column prop="dormNum" label="所属宿舍">
            <template slot-scope="scope">
              <p v-if="scope.row.dormNum==-1">尚未分配寝室</p>
              <p v-if="scope.row.dormNum!=-1">{{scope.row.dormNum}}</p>
            </template>
          </el-table-column>
          <el-table-column prop="lastMoney" label="宿舍水电费余额">
          </el-table-column>
          <el-table-column prop="status" label="寝室状态">
            <template slot-scope="scope">
              {{scope.row.status==0?'正常':'催款中'}}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="320">
            <template slot-scope="scope">
              <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
              <el-button type="text" size="small" @click="centerDialogVisible2=true,changeStu(scope.$index,scope.row)">
                编辑</el-button>
              <el-button type="text" size="small" @click="changeType(scope.$index, scope.row)">发起催款提醒</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>
    <div id="pages">
      <el-pagination @current-change="handleCurrentChange2" @size-change="handlePageSize2" background
        :current-page="currentPage" layout="prev, pager, next" :total="total" :page-size="pagesize">
      </el-pagination>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    var checkNum = (rule, value, callback) => {
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else if (/^1\d{9}$/.test(value) == false) {
        callback(new Error('请输入有效的学号'));
      } else {
        callback();
      }
    };
    var checkName = (rule, value, callback) => {
      if (/^[\u4e00-\u9fa5]+$/.test(value) == false) {
        callback(new Error('请输入中文'));
      } else {
        callback();
      }
    };
    var checkUsername = (rule, value, callback) => {
      if (/^(?![a-zA-Z]+$)[0-9A-Za-z]{4,20}/.test(value) == false) {
        callback(new Error('账号只能是英文和数字的组合'));
      } else {
        callback();
      }
    }
    var checkPass = (rule, value, callback) => {
      if (/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,20}/.test(value) == false) {
        callback(new Error('密码必须是英文和数字的组合'));
      } else {
        callback();
      }
    }
    return {
      // 搜索学生姓名绑定
      name: '',
      // 添加、修改弹出框
      centerDialogVisible: false,
      centerDialogVisible2: false,
      // 分页
      total: 50,
      pagesize: 5,
      currentPage: 1,
      page: 1,
      loading: true,
      list: [

      ],
      // 有效性验证绑定
      ruleForm: {
        stuName: '',
        userName: '',
        password: '',
        account: '',
        dormNum: -1,
        name: '',
        passwd: '',
        stuNum: '',
      },
      ruleForm2: {
        dormNum: '',
        userName: '',
        name: '',
        passwd: '',
        stuNum: '',
        status: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' },
        ],
        stuNum: [
          { validator: checkNum, trigger: 'blur' },
          { required: true, message: '请输入学生学号', trigger: 'blur' },
          // { min: 3, max: 6, message: '请输入有效的学号', trigger: 'blur' }
        ],
        passwd: [
          { validator: checkPass, trigger: 'blur' },
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 20, message: '密码长度必须在4-20位', trigger: 'blur' }
        ],
        account: [
          { validator: checkUsername, trigger: 'blur' },
          { required: true, message: '请输入学生账号', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        dormNum: [
          { required: true, message: '请选择学生所属寝室', trigger: 'change' }
        ],
      },

      StudentData: [
        {
          stuNum: '',
          stuName: '',
          userName: '',
          dormNum: '',
          lastMoney: '',
          status: '',
          password: ''
        }, {
          stuNum: 19610,
          stuName: '101',
          userName: '10111',
          dormNum: 101,
          lastMoney: 4.5,
          status: 1,
          password: ''
        }, {
          stuNum: 19610,
          stuName: '101',
          userName: '10111',
          dormNum: 101,
          lastMoney: 4.5,
          status: 0,
          password: ''
        }, {
          stuNum: 19610,
          stuName: '101',
          userName: '10111',
          dormNum: 101,
          lastMoney: 4.5,
          status: 1
        }, {
          stuNum: 19610,
          stuName: '101',
          userName: '10111',
          dormNum: 101,
          lastMoney: 4.5,
          status: 0,
          password: ''
        }],
    }
  },
  methods: {

    // 添加学生
    test () {
      console.log(this.StudentData.dormNum)
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },

    addStudent () {
      var params = new URLSearchParams();
      params.append('account', this.ruleForm.account)
      params.append('dormNum', this.ruleForm.dormNum)
      params.append('name', this.ruleForm.name)
      params.append('passwd', this.ruleForm.passwd)
      params.append('stuNum', this.ruleForm.stuNum)
      this.$axios.post('/addStu', params).then(res => {
        // console.log(res)
        if (res.data.code == 200) {
          this.$message.success('添加学生成功！')
          this.checkStudent()
          this.checkStudent()
        } else {
          this.$message.error('添加学生失败！')
        }
      })
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // this.$message.success('添加成功！');
          return this.centerDialogVisible = false
        } else {
          this.$message.error('请输入有效数据！');
          return false;
        }
      });
    },


    // 重置

    clearSearch (row, column) {
      this.$refs.search.value = ""
    },


    // 查询所有学生
    handleCurrentChange2 (val) {
      this.currentPage = val
      this.loading = true;
      // console.log('当前页:');
      // console.log(this.currentPage);
      this.checkStudent();
    },
    handlePageSize2 (val) {
      this.currentPage = val
      // console.log('条数:');
      // console.log(val);
      // console.log(this.currentPage);
    },
    checkStudent () {
      // localStorage.getItem("token")
      this.$axios.get('/allStuInfo', {
        params: {
          rows: this.pagesize,
          page: this.currentPage
        },
      }).then(res => {
        console.log(res);

        this.StudentData = res.data.data.students;
        if (res.data.code == 200) {
          this.loading = false;
          this.getDormNum()
        } else {
          this.$message('查询失败')
        }
      })
    },

    // 获取宿舍编号
    getDormNum (val) {
      var list = []
      for (let i in this.StudentData) {
        list.push(this.StudentData[i].dormNum)
      }
      console.log(list)
    },




    // 编辑学生
    changeStu (index, row) {
      this.centerDialogVisible2 = true;
      this.ruleForm2.stuNum = row.stuNum;
      this.ruleForm2.name = row.stuName;
      // console.log(row.stuName)
      this.ruleForm2.userName = row.userName;
      this.ruleForm2.passwd = row.password;
      this.ruleForm2.status = row.status;
      console.log(index, row)
    },
    changeStudent () {
      var params = URLSearchParams()
      params.append('dormNum', this.ruleForm2.dormNum)
      params.append('name', this.ruleForm2.name)
      params.append('passwd', this.ruleForm2.passwd)
      params.append('stuNum', this.ruleForm2.stuNum)
      this.$axios.post('/changeStuInfo', params).then(res => {
        console.log(res)
        if (res.data.code == 200) {
          this.$message.success('修改学生成功！')
        } else {
          this.$message.error('修改学生失败！')
        }
      })
    },

    // 按名字查询学生信息

    checkStuName () {
      var params = new URLSearchParams()
      params.append('name', this.name)
      this.$axios.post('/queryStuByName', params).then(res => {
        console.log(res);
        this.StudentData = res.data.data.stuInfoList;
        if (res.data.code == 200) {
          // this.$message('查询成功')
          console.log()
        } else {
          this.$message('查询失败')
        }
      })
    },



    // 查看学生



    // 获取记录总条数
    chekTotal () {
      // localStorage.getItem("token")
      var params = new URLSearchParams()
      this.$axios.post('/queryTotalCount', params).then(res => {
        // console.log(res);
        this.total = res.data.data.totalCount;
        // console.log(res.data.data.totalCount)
        if (res.data.code == 200) {
          // this.$message('查询成功')
          console.log()
        } else {
          this.$message('查询失败')
        }
      })
    },


    // 更改寝室状态（催款提醒）
    changeType (index, row) {
      if (row.status = "正常") {
        row.status = "催款中";
        // console.log(row.status)
      }
      console.log(index, row)
    },


    // 分页

    handleCurrentChange (val) {
      this.currentRow = val;
    },
    handleClick (row) {
      console.log(row);
    },
    headerStyle ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 15) {
        return 'table-th'
      } else if (columnIndex === 0 || columnIndex === 1) {
        return 'table-lt'
      } else {
        return 'table-rt'
      }
    },
    isCenter ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 15) {
        return 'text-align: center'
      } else if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
        return 'text-align: left'
      } else {
        return 'text-align: right'
      }
    },
  },
  mounted () {
    this.checkStudent();
    this.chekTotal();
  },
}
</script>
<style scoped>
.wrap {
  margin-top: 30px !important;
  border-top: 1px solid #fff;
}
.wrap .el-input {
  width: 400px;
}
::v-deep .el-input input {
  padding-left: 20px !important;
}
.wrap .el-button {
  width: 100px;
  height: 40px;
  line-height: 40px;
}
::v-deep .el-table {
  margin-top: 50px !important;
  font-size: 0.3rem;
}
::v-deep .el-table th {
  border-color: #bbb;
}
::v-deep .el-table tr th,
::v-deep .el-table tr td {
  text-align: center;
}
::v-deep .el-table tr th {
  height: 1rem;
  background: #eee;
}
::v-deep .el-table tr td button {
  width: 1.1rem !important;
}
::v-deep .el-dialog {
  margin: auto auto !important;
  padding-left: 30px !important;
  width: 800px;
  height: 400px;
  position: absolute;
  left: 0px;
  right: 0px;
  top: 0px;
  bottom: 0px;
  overflow: hidden;
}
::v-deep .el-dialog:nth-child(1) {
  height: 550px;
}

::v-deep .el-dialog .el-dialog__header {
  margin-top: 30px !important;
}
::v-deep .el-dialog .el-form-item {
  margin-top: 30px !important;
}
::v-deep .el-dialog .el-dialog__footer {
  margin-top: 70px !important;
}
::v-deep .el-dialog .el-dialog__footer .el-button:nth-child(1) {
  margin-right: 100px !important;
}
::v-deep .el-dialog .el-form-item .el-form-item__content .el-form-item__error {
  margin-left: 100px !important;
  margin-top: 5px !important;
}
::v-deep .el-dialog .el-form-item .el-form-item__content .el-input {
  margin-left: 10px !important;
}
#pages {
  margin-right: 10px !important;
  margin-top: 50px !important;
  float: right;
}
</style>